/***********************************************************************
 * Module:  AbstractResourceProcessor.java
 * Author:  wuxinyang
 * Purpose: Defines the Class AbstractResourceProcessor
 ***********************************************************************/

package com.witframework.plugin.lucene.index;

import java.io.File;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.springframework.util.Assert;

import com.witframework.plugin.lucene.IndexException;


/** ResourceProcessor基类，提供基本的目录设置和索引维护功能
 *
 * @pdOid 42b68c71-ba3e-493b-892f-71121788955b */
public abstract class AbstractResourceProcessor implements ResourceProcessor {
	private static final Log log = LogFactory	.getLog(AbstractResourceProcessor.class);
	private String indexDirectory;
	protected IndexWriter indexWriter;
	private Analyzer analyzer;

	/**
	 * 初始化词语分析器，使用了lucene实现：org.apache.lucene.analysis.cn.ChineseAnalyzer
	 */
	public AbstractResourceProcessor(){
		analyzer=new org.apache.lucene.analysis.cn.ChineseAnalyzer();
	}

	/**
	 * 设置分析器，通过spring Ioc注入。
	 * @param analyzer
	 */
	public void setAnalyzer(Analyzer analyzer) {
		this.analyzer = analyzer;
	}

	/**
	 * 设置索引存放目录。
	 * @param indexDirectory -文件系统目录路径描述字符串
	 */
	public void setIndexDirectory(String indexDirectory){
		if(this.indexDirectory==null||!this.indexDirectory.equals(indexDirectory)){
			this.indexDirectory=indexDirectory;
			try {
				reflush();
			} catch (IOException e) {
				log.error(e.getLocalizedMessage());
			}
		}
	}

	/**
	 * 添加需要索引的Document对象
	 * @param document -Document对象
	 */
	public void addDocument(Document document){
		Assert.hasText(indexDirectory, "please set index directory. ");
		addDocumentInternal(document);
	}
	/**
	 * 处理需要产生索引的Document对象
	 * @param document -Document对象
	 */
	public abstract void addDocumentInternal(Document document);

	/**
	 * 关闭索引产生类IndexWriter对象
	 * 在关闭前执行optimize().
	 */
	public void close() throws IndexException{
		if(indexWriter!=null){
			flush();
			try {
				indexWriter.optimize();
				indexWriter.close();
			} catch (Exception e) {
				log.error(e.getLocalizedMessage());
				throw new IndexException("can not close IndexWriter.",e);
			}

		}
	}

	private void reflush() throws IOException{
		if(indexWriter!=null){
			indexWriter.optimize();
			indexWriter.close();
		}else{
			File   indexDir = new File(indexDirectory);
	        indexWriter = new IndexWriter(indexDir,analyzer,true);
	        //合并因子（mergeFactor）
	        indexWriter.setMergeFactor(1024);
			indexWriter = new IndexWriter(indexDir,analyzer,true);
		}
	}

}